package com.test.springsecurity.controller;


import com.test.springsecurity.util.ResponseResult;
import com.test.springsecurity.util.ResultStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${filedir}")
    private String filerdir;


    @PostMapping("/upload")
    public ResponseResult<String>  upload(MultipartFile headImg){
        log.info(headImg.getOriginalFilename());
        String name = headImg.getOriginalFilename();
        //重新给文件取名字
        String fileName = UUID.randomUUID().toString()+ name.substring(name.lastIndexOf("."));

        //得到文件的路径
        String filepath = filerdir + File.separator + fileName;

        ResponseResult<String> responseResult = new ResponseResult<>();
        //将文件存进去
        try{
            //成功
            headImg.transferTo(new File(filepath));
            responseResult.setCode(200);
            responseResult.setMessage("上传成功");
            responseResult.setData(fileName);
            responseResult.setResultStatus(ResultStatus.SUCCESS);
        }catch (Exception e){
            //失败
            responseResult.setCode(500);
            responseResult.setMessage("上传失败");
            responseResult.setResultStatus(ResultStatus.FAIL);
            e.printStackTrace();
        }
        return responseResult;
    }
}
